package org.example.blog.controller;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.example.blog.enmus.ResultCodeEnum;
import org.example.blog.mapper.UserInfoMapper;
import org.example.blog.model.BlogInfo;
import org.example.blog.model.Result;
import org.example.blog.model.UserInfo;
import org.example.blog.service.UserService;
import org.example.blog.utils.JwtUtils;
import org.example.blog.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RequestMapping("/user")
@RestController
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private UserInfoMapper userInfoMapper;

    @RequestMapping("/login")
    public Result login(String userName, String password) {
//        Assert.hasLength(userName,"用户名不能为空");
//        crt+all  看源码处理异常
//        Assert.hasLength(password,"密码不能为空");
//        验证--不能为空
        if (!StringUtils.hasLength(userName) || !StringUtils.hasLength(password)){
            return Result.fail(ResultCodeEnum.PARAM_INVALID.getCode(), "账号或者密码不能为空");
        }
//        验证账号密码是否正确
        UserInfo userInfo = userService.selectUserInfoByName(userName);
        if (userInfo == null || userInfo.getId()==null){
            return Result.fail(ResultCodeEnum.PARAM_INVALID.getCode(), "用户不存在");
        }
//        判断密码是否正确
//        if (!password.equals(userInfo.getPassWord())){
//            return Result.fail(ResultCodeEnum.PARAM_INVALID.getCode(), "密码错误");
//        }
        if (!SecurityUtils.verify(password,userInfo.getPassWord())){
            return Result.fail(ResultCodeEnum.PARAM_INVALID.getCode(), "密码错误");
        }

//        账号密码正确
        Map<String, Object> cliams = new HashMap<>();
        cliams.put("id", userInfo.getId());
        cliams.put("name", userInfo.getUserName());

        String jwt = JwtUtils.genJwt(cliams);
        return Result.success(jwt);
    }

    @RequestMapping("/getUserInfo")
    public UserInfo getUserInfo(HttpServletRequest request){
//        从token获取id
        String userToken  = request.getHeader("user_token_header");
        Integer userId = JwtUtils.GetUserIdFromToken(userToken);
//        判断userid
        Assert.notNull(userId,"用户未登录");
        UserInfo userInfo = userService.selectUserInfoById(userId);
        return userInfo;
    }

    @RequestMapping("/getAuthorInfo")
    public UserInfo getAuthorInfo(Integer blogId){
        log.info("接受参数，blogId："+blogId);
        Assert.notNull(blogId,"博客ID不能为空");
        return userService.selectAuthorInfoByBlogId(blogId);
    }

}
